﻿using BusinessEntity;
using BusinessEntity.xmglQuerryEntity;
using BusinessRepository;
using BusinessRule.Organization;
using learun.util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace BusinessRule
{
    public class ProGuiDangRule
    {
        #region 归档

        #region 导出
        /// <summary>
        /// 用户列表（导出Excel）
        /// </summary>
        /// <returns></returns>
        public static async Task<MemoryStream> GetExportxmgdList(List<string> ids, List<ColumnModel> cols)
        {
            //List<string> ids = new List<string>();
            //List<ColumnModel> cols = new List<ColumnModel>();

            //取出数据源
            DataTable exportTable = await GetExportxmgdList(ids);
            //设置导出格式
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.Title = "项目归档";
            excelconfig.TitleFont = "微软雅黑";
            excelconfig.TitlePoint = 25;
            //excelconfig.HeadPoint = 12;
            excelconfig.FileName = "项目归档.xls";
            excelconfig.IsAllSizeColumn = true;
            //每一列的设置,没有设置的列信息，系统将按datatable中的列名导出
            excelconfig.ColumnEntity = new List<ColumnModel>();
            for (int i = 0; i < cols.Count; i++)
            {
                excelconfig.ColumnEntity.Add(new ColumnModel() { Column = cols[i].Column, ExcelColumn = cols[i].ExcelColumn });
            }

            return ExcelHelper.ExportMemoryStream(exportTable, excelconfig);
        }

        public async static Task<DataTable> GetExportxmgdList(List<string> ids)
        {
            //throw new NotImplementedException();
            string yids = string.Join("','", ids);
            yids = "'" + yids + "'";
            string strsql = "select * from View_proguidang where xmid in (" + yids + ")";
            return await new RepositoryFactory().BaseRepository().FindTable(strsql);
        }

        #endregion

        public static async Task<(IEnumerable<dynamic> list, int total)> GetXMGDIndexList(dynamic dye, string strdepids)
        {
            //dye.xmmc = xmmc;
            //dye.xmfzr = xmfzr;
            //dye.status = status;
            //dye.current = current;
            //dye.size = size;
            //dye.sort = sort;
            //dye.column = column;

            string strxmmc = dye.xmmc;
            string xmfzr = dye.xmfzr;
            string status = dye.status;
            string gdstatus = dye.gdstatus;

            string xmnf = dye.xmnf;
            string jsdw = dye.jsdw;
            string xmflname = dye.xmflname;
 


            string current = dye.current;
            string size = dye.size;
            string sort = dye.sort ?? "";
            string column = dye.column ?? "";


            string str = "";
            if (!(string.IsNullOrEmpty(strxmmc)))
            {
                str = str + " and xmmc like '%" + strxmmc + "%'";
            }

            if (!(string.IsNullOrEmpty(xmfzr)))
            {
                str = str + " and ProjectManager like '%" + xmfzr + "%'";
            }

            if (!(string.IsNullOrEmpty(status)))
            {
                //str += status == "1" ? " and gdstatus= '归档'" : " and gdstatus= '未归档'";
                str += " and spstatus= '" + status + "'";
            }

            if (!(string.IsNullOrEmpty(gdstatus)))
            {
                str += " and gdstatusn= '" + gdstatus + "'";
            }

            if (!(string.IsNullOrEmpty(xmnf)))
            {
                str += " and xmnf= '" + xmnf + "'";
            }
            if (!(string.IsNullOrEmpty(jsdw)))
            {
                str += " and jsdw= '" + jsdw + "'";
            }
            if (!(string.IsNullOrEmpty(xmflname)))
            {
                str += " and xmflname= '" + xmflname + "'";
            }


            //await UserRule.GetUserDepid(uid)
            string sql = "select * from View_proguidang where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str.Replace("''", "'");
            bool isAsc = true;
            if (sort != "Asc" && sort != "asc")
            {
                isAsc = false;
            }
            if (string.IsNullOrEmpty(column))
            {
                column = "id";
            }
            return await new RepositoryFactory().BaseRepository().FindList(sql, null, column, isAsc, size.ToInt(), current.ToInt());

        }

        //查询选择合同列表
        //public static async Task<(DataTable, int)> GetHTIndexList(ProHeTongQuerry querry, string strdepids)
        public static async Task<(IEnumerable<dynamic>, int)> GetXZHTIndexList(dynamic querry, string strdepids)
        {
            string str = "";

            string xmid = querry.xmid;
            string gdid = querry.gdid;

            string current = querry.current;
            string size = querry.size;
            string sort = querry.sort ?? "";
            string column = querry.column ?? "";

            if (!(string.IsNullOrEmpty(xmid)))
            {
                str = str + " and xmid = ''" + xmid + "''";
            }
            if (!(string.IsNullOrEmpty(gdid)))
            {
                str = str + " and xmid in (select xmid from CProGD where id = ''" + gdid + "'')";
            }

            string sql = "select * from View_ProFKLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str.Replace("''", "'");
            bool isAsc = true;
            if (sort != "Asc" && sort != "asc")
            {
                isAsc = false;
            }
            if (string.IsNullOrEmpty(column))
            {
                column = "id";
            }
            return await new RepositoryFactory().BaseRepository().FindList(sql, null, column, isAsc, size.ToInt(), current.ToInt());
        }

        public async static Task<dynamic> GetXMGDByxmid(string xmid)
        {
            string strsql = "select * from View_proguidang where xmid = '" + xmid + "'";

            return await new RepositoryFactory().BaseRepository().FindEntity(strsql);
        }

        public async static Task<dynamic> GetXMGDByid(string gdid)
        {
            string strsql = "select * from View_proguidang where id = '" + gdid + "'";

            return await new RepositoryFactory().BaseRepository().FindEntity(strsql);
        }

        public async static Task<DataTable> GetXMGDMoneyByxmid(string xmid)
        {
            string strsql = "select * from view_XMHTFKJE where id = '" + xmid + "'";

            return await new RepositoryFactory().BaseRepository().FindTable(strsql);
        }

        public async static Task<DataTable> GetXMGDMoneyByGDid(string gdid)
        {
            string strsql = "select * from view_XMHTFKJE where gdid = '" + gdid + "'";

            return await new RepositoryFactory().BaseRepository().FindTable(strsql);
        }

        public async static Task<bool> InsertxmgdMul(List<CProGD> gds, string ope)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                for (int i = 0; i < gds.Count; i++)
                {
                    //先删除
                    string strsql = "delete from CProGD where xmid = '" + gds[i].xmid + "'";
                    await irp.ExecuteSql(strsql);

                    //再新增
                    await irp.Insert(gds[i]);
                }

                return true;
            });
        }

        public async static Task<bool> Insertxmgd(CProGD log, string ope)
        {
            if (ope == "add")
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    //先删除
                    string strsql = "delete from CProGD where xmid = '" + log.xmid + "'";
                    await irp.ExecuteSql(strsql);

                    //再新增
                    await irp.Insert(log);
         
                    return true;

                }); 
            }
            else// (ope == "edit")
            {
                await new RepositoryFactory().BaseRepository().Update(log);
                return true;
            }
        }

        public async static Task<bool> DeleteXMGD(Root ids)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    await irp.DeleteAny<CProGD>(new { id = idm.id });


                }
                return true;
            });
        }

        public async static Task<List<string>> GetXMDXHTID(string xmid)
        {
            string strsql = "exec getprojectids '"+ xmid + "'";
            DataTable dts = await new RepositoryFactory().BaseRepository().FindTable(strsql);
            List<string> list = new List<string>();
            for (int i = 0; i < dts.Rows.Count; i++)
            {
                list.Add(dts.Rows[i]["id"].ToString());
            }

            return list;
        }


        #endregion

        #region 决算

        #region 导出
        /// <summary>
        /// 用户列表（导出Excel）
        /// </summary>
        /// <returns></returns>
        public static async Task<MemoryStream> GetExportxmjusList(List<string> ids, List<ColumnModel> cols)
        {
            //List<string> ids = new List<string>();
            //List<ColumnModel> cols = new List<ColumnModel>();

            //取出数据源
            DataTable exportTable = await GetExportxmjusList(ids);
            //设置导出格式
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.Title = "项目决算";
            excelconfig.TitleFont = "微软雅黑";
            excelconfig.TitlePoint = 25;
            //excelconfig.HeadPoint = 12;
            excelconfig.FileName = "项目决算.xls";
            excelconfig.IsAllSizeColumn = true;
            //每一列的设置,没有设置的列信息，系统将按datatable中的列名导出
            excelconfig.ColumnEntity = new List<ColumnModel>();
            for (int i = 0; i < cols.Count; i++)
            {
                excelconfig.ColumnEntity.Add(new ColumnModel() { Column = cols[i].Column, ExcelColumn = cols[i].ExcelColumn });
            }

            return ExcelHelper.ExportMemoryStream(exportTable, excelconfig);
        }

        public async static Task<DataTable> GetExportxmjusList(List<string> ids)
        {
            //throw new NotImplementedException();
            string yids = string.Join("','", ids);
            yids = "'" + yids + "'";
            string strsql = "select * from View_ProJuSLists where xmid in (" + yids + ")";
            return await new RepositoryFactory().BaseRepository().FindTable(strsql);
        }

        #endregion

        public static async Task<(IEnumerable<dynamic> list, int total)> GetXMJusIndexList(dynamic dye, string strdepids)
        {
            string strxmmc = dye.xmmc;
            string xmfzr = dye.xmfzr;
            string status = dye.status;
            string current = dye.current;
            string size = dye.size;
            string sort = dye.sort ?? "";
            string column = dye.column ?? "";

            string str = "";
            if (!(string.IsNullOrEmpty(strxmmc)))
            {
                str = str + " and xmmc like '%" + strxmmc + "%'";
            }

            if (!(string.IsNullOrEmpty(xmfzr)))
            {
                str = str + " and ProjectManager like '%" + xmfzr + "%'";
            }

            if (!(string.IsNullOrEmpty(status)))
            {
                str += status == "1" ? " and jusstatus= '决算'" : " and jusstatus= '未决算'";
            }



            //await UserRule.GetUserDepid(uid)
            string sql = "select * from View_ProJuSLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str.Replace("''", "'");
            bool isAsc = true;
            if (sort != "Asc" && sort != "asc")
            {
                isAsc = false;
            }
            if (string.IsNullOrEmpty(column))
            {
                column = "id";
            }
            return await new RepositoryFactory().BaseRepository().FindList(sql, null, column, isAsc, size.ToInt(), current.ToInt());

        }

        public async static Task<IEnumerable<dynamic>> GetXMJueSMXByjsid(string jsid)
        {
            //throw new NotImplementedException();
            string strsql = "select id, jusid, jsmx, units, nums, prices,mxje, bz from CProJuSMX where jusid= '" + jsid + "'";
            return await new RepositoryFactory().BaseRepository().FindList(strsql);
        }

        public async static Task<dynamic> GetXMJueSByxmid(string xmid)
        {
            //throw new NotImplementedException();
            string strsql = "select id,xmid,sbjsje,sbjsrq,status,jusstatus,spstatus from View_ProJuSLists where xmid= '" + xmid + "'";
            return await new RepositoryFactory().BaseRepository().FindEntity(strsql);
        }

        public async static Task<dynamic> GetXMJueSByid(string jid)
        {
            string strsql = "select id,xmid,sbjsje,sbjsrq,status,jusstatus,spstatus from View_ProJuSLists where id = '" + jid + "'";
            return await new RepositoryFactory().BaseRepository().FindEntity(strsql);
        }

        public async static Task<bool> InsertXMJueS(CProJUS jus, List<CProJuSMX> jsmx, string strope)
        {
            if (strope == "add")
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    //删除决算信息
                    string strsql = "delete CProJuSMX where jusid in (select id from CProJUS where xmid = '" + jus.xmid + "')";
                    await irp.ExecuteSql(strsql);

                    strsql = "delete from CProJUS where xmid = '" + jus.xmid + "'";
                    await irp.ExecuteSql(strsql);

                    //新增决算
                    await irp.Insert(jus);

                    //新增决算明细
                    for (int i = 0; i < jsmx.Count; i++)
                    {
                        jsmx[i].jusid = jus.id;

                        await irp.Insert(jsmx[i]);
                    }

                    return true;

                });
            }
            else
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    //删除决算信息
                    string strsql = "delete CProJuSMX where jusid = '" + jus.id + "'";
                    await irp.ExecuteSql(strsql);

                    //strsql = "delete from CProJUS where xmid = '" + jus.xmid + "'";
                    //await irp.ExecuteSql(strsql);

                    //修改决算
                    await irp.Update(jus);

                    //新增决算明细
                    for (int i = 0; i < jsmx.Count; i++)
                    {
                        jsmx[i].jusid = jus.id;

                        await irp.Insert(jsmx[i]);
                    }

                    return true;

                });
            }
        }

        public async static Task<bool> DeleteXMJusMulti(Root ids)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    await irp.DeleteAny<CProJuSMX>(new { jusid = idm.id });
                    await irp.DeleteAny<CProJUS>(new { id = idm.id });
                }
                return true;
            });

        }
        #endregion
    }
}
